home *** CD-ROM | disk | FTP | other *** search
-
- /*
- * qsort.c
- *
- * Copyright (c) 1991 Symantec Corporation. All rights reserved.
- *
- */
-
- #include "stdlib.h"
-
- static char *qBase;
- static size_t qSize;
- static __cmp_func qCompare;
-
- static int std_compare(size_t, size_t);
- static void std_swap(size_t, size_t);
-
- static void qsort1(size_t, size_t);
- static __cmp1_func q1Compare;
- static __swap1_func q1Swap;
-
-
- /* ---------- standard quicksort ---------- */
-
-
- void
- qsort(void *base, size_t n, size_t size, __cmp_func compare)
- {
- qBase = base;
- qSize = size;
- qCompare = compare;
- _qsort(n, std_compare, std_swap);
- }
-
-
- static int
- std_compare(size_t i, size_t j)
- {
- return((*qCompare)(qBase + i * qSize, qBase + j * qSize));
- }
-
-
- static void
- std_swap(size_t i, size_t j)
- {
- register size_t size = qSize;
- register void *p = qBase + i * size;
- register void *q = qBase + j * size;
-
- asm {
- @1 move.b (p),d0
- move.b (q),(p)+
- move.b d0,(q)+
- subq.l #1,size
- bne.s @1
- }
- }
-
-
- /* ---------- general quicksort ---------- */
-
-
- void
- _qsort(size_t n, __cmp1_func compare, __swap1_func swap)
- {
- q1Compare = compare;
- q1Swap = swap;
- qsort1(0, n);
- }
-
-
- /*
- * sort elements "first" through "last"-1
- *
- */
-
- static void
- qsort1(size_t first, size_t last)
- {
- static size_t i; /* "static" to save stack space */
- size_t j;
-
- while (last - first > 1) {
- i = first;
- j = last;
- for (;;) {
- while (++i < last && (*q1Compare)(i, first) < 0)
- ;
- while (--j > first && (*q1Compare)(j, first) > 0)
- ;
- if (i >= j)
- break;
- (*q1Swap)(i, j);
- }
- if (j == first) {
- ++first;
- continue;
- }
- (*q1Swap)(first, j);
- if (j - first < last - (j + 1)) {
- qsort1(first, j);
- first = j + 1; /* qsort1(j + 1, last); */
- }
- else {
- qsort1(j + 1, last);
- last = j; /* qsort1(first, j); */
- }
- }
- }
-